package com.blueocean_health.care.management.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.X509TrustManager;

import org.apache.http.HttpStatus;
import org.jsoup.Connection;
import org.jsoup.Connection.Response;
import org.jsoup.Jsoup;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.blueocean_health.care.management.common.base.em.TimeType;
import com.blueocean_health.care.management.common.base.string.StringUtils;
import com.blueocean_health.care.management.common.base.time.TimeUtils;
import com.blueocean_health.care.management.domain.base.SysResult;

/**
 * 请求网络的一些简单方法
 *
 *
 * @Title: JsoupUtils.java
 * @Package com.blueocean_health.care.management.utils
 * @author luxue
 * @date 2018年8月14日
 * @version V1.0
 */
public class JsoupUtils {

	/**
	 * 网络请求方法, 返回string @Title: postConnect @param url @param obj @return @throws
	 * IOException @version V1.0 @throws
	 */
	public static String postConnectToString(String url, Object obj) throws IOException {
		Connection connect = Jsoup.connect(url).timeout(50000);
		connect.method(Connection.Method.POST).header("Content-Type", "application/json;charset=UTF-8");
		if (!StringUtils.isEmpty(obj)) {
			connect.requestBody(JSON.toJSONString(obj));
		}
		return connect.ignoreContentType(true).execute().body();
	}
	
	/**
	 * 网络请求方法
	 * @Title: postConnect 
	 * @param url 
	 * @param obj 
	 * @return 
	 * @throws IOException 
	 * @version V1.0.7 
	 */
	public static Response doPostFileResponse(String url, Object obj) throws IOException {
		Connection connect = Jsoup.connect(url).timeout(50000);
		connect.method(Connection.Method.POST).header("Content-Type", "application/json;charset=UTF-8");;
		if (!StringUtils.isEmpty(obj)) {
			connect.requestBody(JSON.toJSONString(obj));
		}
		return connect.ignoreContentType(true).execute();
	}

	/**
	 * 网络请求方法，返回SysResult @Title: postConnectToSysResult @param url @param
	 * obj @return @throws IOException SysResult @version V1.0 @throws
	 */
	public static SysResult postConnectToSysResult(String url, Object obj) throws IOException {
		return JSON.parseObject(postConnectToString(url, obj), SysResult.class);
	}

	/**
	 * 文件上传
	 * 
	 * @param url              请求的Url
	 * @param paramMap         参数
	 * @param file             文件
	 * @param fileRequestParam form表单对应的文件name属性名
	 * @return
	 * @throws Exception
	 */
	public static SysResult doPostFileRequestToSysResult(String url, Map<String, String> paramMap, MultipartFile file,
			String fileRequestParam) throws Exception {
		return JSON.parseObject(doPostFileRequest(url, paramMap, file, fileRequestParam).body(), SysResult.class);
	}

	/**
	 * 文件上传
	 * 
	 * @param url              请求的Url
	 * @param paramMap         参数
	 * @param file             文件
	 * @param fileRequestParam form表单对应的文件name属性名
	 * @return
	 * @throws Exception
	 */
	public static Response doPostFileRequest(String url, Map<String, String> paramMap, MultipartFile file,
			String fileRequestParam) throws Exception {
		if (StringUtils.isEmpty(url)) {
			throw new Exception("The request URL is blank.");
		}
		// Https请求
		if (url.toLowerCase().startsWith("https")) {
			trustEveryone();
		}
		Connection connection = Jsoup.connect(url);
		connection.method(Connection.Method.POST);
		connection.timeout(50000);
//		connection.header("Content-Type", "multipart/form-data");
		connection.ignoreHttpErrors(true);
		connection.ignoreContentType(true);
		if (paramMap != null && !paramMap.isEmpty()) {
			connection.data(paramMap);
		}
		try {
			connection.data(fileRequestParam, file.getOriginalFilename(), file.getInputStream());
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		try {
			Response response = connection.execute();
			if (response.statusCode() != HttpStatus.SC_OK) {
				throw new Exception("http请求响应码:" + response.statusCode() + "");
			}
			return response;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 文件上传
	 * 
	 * @param url              请求的Url
	 * @param paramMap         参数
	 * @param file             文件
	 * @param fileRequestParam form表单对应的文件name属性名
	 * @return
	 * @throws Exception
	 */
	public static Response doPostFileRequest(String url, Map<String, String> paramMap, File file,
			String fileRequestParam) throws Exception {
		if (StringUtils.isEmpty(url)) {
			throw new Exception("The request URL is blank.");
		}
		// Https请求
		if (url.toLowerCase().startsWith("https")) {
			trustEveryone();
		}
		Connection connection = Jsoup.connect(url);
		connection.method(Connection.Method.POST);
		connection.timeout(12000);
//		connection.header("Content-Type", "multipart/form-data");
		connection.ignoreHttpErrors(true);
		connection.ignoreContentType(true);
		if (paramMap != null && !paramMap.isEmpty()) {
			connection.data(paramMap);
		}
		try {
			FileInputStream fis = new FileInputStream(file);
			connection.data(fileRequestParam, file.getName(), fis);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		try {
			Response response = connection.execute();
			if (response.statusCode() != HttpStatus.SC_OK) {
				throw new Exception("http请求响应码:" + response.statusCode() + "");
			}
			return response;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 解决Https请求,返回404错误
	 */
	private static void trustEveryone() {
		try {
			HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {

				public boolean verify(String hostname, SSLSession session) {
					return true;
				}
			});
			SSLContext context = SSLContext.getInstance("TLS");
			context.init(null, new X509TrustManager[] { new X509TrustManager() {

				public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
				}

				public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
				}

				public X509Certificate[] getAcceptedIssuers() {
					return new X509Certificate[0];
				}
			} }, new SecureRandom());
			HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
